#include "electronicscalerecorder.h"
#include <QDateTime>
#include <QDebug>

ElectronicScaleRecorder::ElectronicScaleRecorder(QObject *parent)
    : QObject(parent)
{
    m_excelEngine = new ExcelEngine(this);
}

ElectronicScaleRecorder::~ElectronicScaleRecorder()
{
    delete m_excelEngine;
}

void ElectronicScaleRecorder::setFileName(const QString &str)
{
    m_fileName = str;
}

QString ElectronicScaleRecorder::getFileName() const
{
    return m_fileName;
}

void ElectronicScaleRecorder::setPeriod(quint32 second)
{
    m_period = second;
}

quint32 ElectronicScaleRecorder::getPeriod() const
{
    return m_period;
}

bool ElectronicScaleRecorder::isRecording() const
{
    return m_isRecording;
}

bool ElectronicScaleRecorder::start()
{
    bool ret = false;
    if (m_excelEngine->Open(m_fileName))
    {
        m_isRecording = true;
        m_periodCnt = 0;
        ret = true;
    }
    return ret;
}

bool ElectronicScaleRecorder::stop()
{
    bool ret = false;
    if (m_isRecording)
    {
        m_isRecording = false;
        m_excelEngine->Close();
        ret = true;
    }
    return ret;
}

bool ElectronicScaleRecorder::saveOneRecord(electronicscale::Sample sample)
{
    bool ret = false;
    if (m_excelEngine->IsValid())
    {
        int row = m_excelEngine->GetRowCount();
        QVariant var;
        var.setValue(QDateTime::fromMSecsSinceEpoch(sample.time).toString("yyyy-MM-dd hh:mm:ss.zzz"));
        m_excelEngine->SetCellData(row + 1, 1, var);
        var.clear();
        var.setValue(sample.weight.value);
        m_excelEngine->SetCellData(row + 1, 2, var);
        QString unit;
        if (sample.weight.unit == electronicscale::WeightUnit::WeightUnit_g)
            unit = "g";
        else if (sample.weight.unit == electronicscale::WeightUnit::WeightUnit_ct)
            unit = "ct";
        var.clear();
        var.setValue(unit);
        m_excelEngine->SetCellData(row + 1, 3, var);
        m_excelEngine->Save();

        ret = true;
    }
    return ret;
}

void ElectronicScaleRecorder::onTimeout()
{
    m_periodCnt++;
    if (m_periodCnt >= m_period)
    {
        m_isRecording = false;
    }
}
